<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../data-jelly-fish/css/layui.css">
</head>
<body  style="margin:20px;">
    <form class="layui-form" action="" lay-filter="example">
        <input type="hidden" name="createTime" class="layui-input">
        <div class="layui-form-item">
            <label class="layui-form-label">TOPIC选择</label>
            <div class="layui-input-inline">
                <select name="topicId" lay-verify="required" lay-search="">
                    <option value="">直接选择或搜索选择</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">表空间</label>
            <div class="layui-input-block">
                <input type="text" name="table" lay-verify="title" autocomplete="off" placeholder="请输入表空间" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">名称</label>
            <div class="layui-input-block">
                <input type="text" name="name" lay-verify="title" autocomplete="off" placeholder="请输入名称" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">推送地址</label>
            <div class="layui-input-block">
                <input type="text" name="url" lay-verify="title" autocomplete="off" placeholder="请输入推送地址" class="layui-input">
            </div>
        </div>

        <div class="layui-collapse" lay-accordion>
            <div class="layui-colla-item">
                <h2 class="layui-colla-title">高级设置</h2>
                <div class="layui-colla-content" style="padding-left: 0px;">

                    <div class="layui-form-item">
                        <label class="layui-form-label">数据过滤</label>
                        <div class="layui-input-block">
                            <input type="text" name="subscribeFilter" lay-verify="title" autocomplete="off" value="{}" placeholder="请输入推送地址" class="layui-input">
                            <label >订阅数据来自于Topic中，可根据数据进行过滤,例：{"account":"123"}</label>
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">告警地址</label>
                        <div class="layui-input-block">
                            <input type="text" name="warningUrl" lay-verify="title" autocomplete="off" placeholder="请输入告警地址" class="layui-input">
                            <label >发生异常时 会以POST JSON BODY 格式 将异常信息推送到此地址</label>
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">去重字段</label>
                        <div class="layui-input-block">
                            <input type="text" name="uniqueFields" lay-verify="title" value="*" autocomplete="off" placeholder="多个用逗号分隔" class="layui-input">
                            <label >对存储的数据进行去重存储，也可用于确认唯一键，默认值 "*" 表示将按整条记录MD5值来做去重标识，指定字段按照 "id,name" 格式，多个字段用逗号分隔</label>
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">最大重试次数</label>
                        <div class="layui-input-block">
                            <input type="text" name="maxTimes" lay-verify="title" value="3" autocomplete="off" placeholder="请输入最大重试次数" class="layui-input">
                            <label >尝试推送多次失败的上限值，超过时数据将会被丢弃不再推送</label>
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">重试延迟(秒)</label>
                        <div class="layui-input-block">
                            <input type="text" name="delay" lay-verify="title" autocomplete="off" value="300" placeholder="请输入重试延迟" class="layui-input">
                            <label >推送失败后重试的时间间隔</label>
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">缓存天数</label>
                        <div class="layui-input-block">
                            <input type="text" name="cacheDay" lay-verify="title" value="-1" autocomplete="off" placeholder="请输入缓存天数" class="layui-input">
                            <label>缓存有效期，默认值-1表示永不过期</label>
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">首次延迟</label>
                        <div class="layui-input-block">
                            <input type="checkbox" name="isFirstDelay" lay-skin="switch" lay-text="ON|OFF" >
                            <p>第一次推送的时间是入库时间还是延迟后的时间，用于在更新多表或多库的网络延迟的业务场景,首次延迟的时间等于重试延迟的时间</p>
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">指数级重试</label>
                        <div class="layui-input-block">
                            <input type="checkbox" checked="" name="isExponent" lay-skin="switch" lay-text="ON|OFF" >
                            <p >是否启用指数级别重试策略，启用后，下一次的重试间隔 = 1<<重试次数 * 重试延迟</p>
                        </div>
                    </div>



                    <div class="layui-form-item">
                        <label class="layui-form-label">启用</label>
                        <div class="layui-input-block">
                            <input type="checkbox" checked=""  name="status" lay-skin="switch" lay-text="ON|OFF" >
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
            <legend style="font-size: 15px;font-weight: bold">任务分片，至少1个</legend>
        </fieldset>
        <table class="layui-table" id="test" lay-filter="test"></table>
        <button type="button" onclick="shardingAdd()" class="layui-btn">添加</button>

        <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">

        </fieldset>
        <div style="text-align: right;">
            <button type="button" onclick="saveConsumer()" class="layui-btn layui-btn-normal">保存</button>
            <button type="button" onclick="cloneConsumer()" id="cloneBtn" style="display: none" class="layui-btn layui-btn-normal">克隆</button>
        </div>
    </form>
<script src="../data-jelly-fish/layui.js"></script>
<script>
    var $;
    layui.use('element', function(){
        $ = layui.jquery
            ,element = layui.element; //Tab的切换功能，切换事件监听等，需要依赖element模块
    });

    var table  = null;
    var form;
    layui.use('form', function(){
        form = layui.form;
    });
    layui.use('table', function(){
        $ = layui.jquery;

        init();
         table = layui.table;
        table.render({
            elem: '#test'
            ,cellMinWidth: 80
            ,data:[
                {
                    "key":"shard1",
                    "filter":'{}'
                }
            ]
            ,cols: [
                [
                    {field:'key',  title: 'key',edit: 'text'}
                    ,{field:'filter', width:500, title: 'filter',edit: 'json'}
                    ,{fixed: 'right', width:178, align:'center', toolbar: '#barDemo',  title: '操作'}
                ]
            ]
        });


        table.on('tool(test)', function (obj) {
            if(obj.event === "del"){
                var oldData = table.cache["test"];
                oldData.splice(obj.tr.data('index'),1);
                layer.msg("删除成功",{time: 500},function(){
                    table.reload('test',{data : oldData});
                });
            }
        });

    });

    var id ;

    function init(){
        id = getUrlParam().id;
        if (id){
            $("#cloneBtn").show()
        }
        var topicId = getUrlParam().topicId;
        $.get("../topic/select",function (data) {
            if(!data.data){
                return;
            }

            $.each(data.data,function (index,item) {
                $("[name='topicId']").append('<option value="'+item.id+'">'+item.name+'</option>')
            })

            if (topicId){
                $("[name='topicId']").find("option[value="+topicId+"]").prop("selected",true);
            }

            layui.form.render('select');

            //表单赋值
            if (id){
                $.get("../consumer/"+id,function (data) {
                    if(!data.data){
                        return;
                    }
                    form.val('example', data.data);
                    table.reload('test', {data: data.data.shardings});
                })
            }
        })


    }

    /* -------function-------- */
    function shardingAdd() {
        var tabledata = table.cache["test"];

        var key = "shard1";
        if (tabledata.length>0){
            var lastData = tabledata[tabledata.length-1];
            var suffixNum = lastData.key.match(/\d*$/)[0];
            if (suffixNum){
                var prefix = lastData.key.replace(/\d*$/,"");
                key = prefix + (parseInt(suffixNum)+1);
            }
        }

        tabledata.push({
            "key":key,
            "filter":"{}"
        })
        table.reload('test', {data: tabledata});
    }

    function getUrlParam() {
        let query = window.location.search.substring(1);
        let vars = query.split("&");
        let urlParam = {};
        for (let i=0;i<vars.length;i++) {
            let pair = vars[i].split("=");
            urlParam[pair[0]] = pair[1];
        }
        return urlParam;
    }

    function cloneConsumer() {
        id = null;
        var formData = form.val('example');
        formData.name = (formData.name +"_COPY");
        formData.table = (formData.table +"_COPY");
        form.val('example', formData);
        $("#cloneBtn").hide();
    }

    function saveConsumer() {
        var formData = form.val('example');
        var data = {
            "id":id,
            "topicId":formData.topicId,
            "table":formData.table,
            "name":formData.name,
            "url":formData.url,
            "subscribeFilter":formData.subscribeFilter,
            "uniqueFields":formData.uniqueFields,
            "warningUrl":formData.warningUrl,
            "maxTimes":formData.maxTimes,
            "createTime":formData.createTime,
            "isFirstDelay":formData.isFirstDelay == "on"?1:0,
            "delay":formData.delay,
            "isExponent":formData.isExponent == "on"?1:0,
            "status":formData.status == "on"?1:0,
            "shardings": table.cache["test"]
        }

        $.ajax({
            type: "POST",
            url: "../consumer",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(data),
            dataType: "json",
            success: function (message) {
                if (message.code == 0){
                    layer.msg('保存成功',{time: 500});
                    var index = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(index);
                    parent.layui.table.reload('test');
                }else{
                    layer.msg('保存异常',{time: 500});
                }
            }
        });
    }
</script>
<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<style type="text/css">
    .layui-form-label{
        width:170px;
    }
    .layui-input-block{
        margin-left:200px;
    }
</style>
</body>
</html>
